package model

import (
	"blog/errmsg"
	"github.com/jinzhu/gorm"
)

type ArticleCategory struct {
	Id uint `gorm:"primary_key;auto_increment;not null" json:"id"`
	Name string `gorm:"type:varchar(20);not null" json:"name"`
}

func CheckCategory(name string)(code int,msg string){
	var category ArticleCategory
	if err := db.Select("id").Where("name = ?",name).First(&category).Error;err!=nil && err!=gorm.ErrRecordNotFound{
		return errmsg.FAIL,err.Error()
	}
	if category.Id > 0{
		return errmsg.FAIL,"该分类名已存在！"
	}
	return errmsg.SUCCESS,""
}
func AddCategory(category *ArticleCategory)(code int,msg string){
	code,msg = CheckCategory(category.Name)
	if code == errmsg.SUCCESS{
		if err := db.Create(category).Error;err!=nil{
			return errmsg.FAIL,"添加分类名称失败 "+err.Error()
		}
		return errmsg.SUCCESS,""
	}
	return
}
func GetCategory(name string)(int,string,*ArticleCategory){
	var category ArticleCategory
	if err := db.Where("name = ?",name).First(&category).Error;err!=nil{
		return errmsg.FAIL,err.Error(),nil
	}
	return errmsg.SUCCESS,"",&category
}
func GetCategorys(page,pagesize int)(int,string,[]ArticleCategory,int){
	var categorys []ArticleCategory
	var total int
	if err := db.Offset((page-1)*pagesize).Limit(pagesize).Find(&categorys).Count(&total).Error;err!=nil && err!=gorm.ErrRecordNotFound{
		return errmsg.FAIL,err.Error(),nil,0
	}
	return errmsg.SUCCESS,"",categorys,total
}
func UpdateCategory(id int,name string)(int,string){
	code,msg := CheckCategory(name)
	if code == errmsg.SUCCESS{
		if err := db.Model(&ArticleCategory{}).Where("id = ?",id).Update("name",name).Error;err!=nil{
			if err==gorm.ErrRecordNotFound {
				return errmsg.FAIL,"该分类不存在！"
			}
			return errmsg.FAIL,err.Error()
		}
		return errmsg.SUCCESS,""
	}
	return code,msg
}
func DeleteCategory(id int)(int,string){
	ddb := db.Where("id = ?",id).Delete(&ArticleCategory{})
	if err := ddb.Error;err!=nil{
		return errmsg.FAIL,err.Error()
	}
	if ddb.RowsAffected == 0{
		return errmsg.FAIL,"删除失败，此id不存在！"
	}
	return errmsg.SUCCESS,""
}